import React, {useEffect, useState} from 'react';
import Nav from "../components/Nav";
import Container from "@material-ui/core/Container";
import {useHistory} from 'react-router-dom'
import {useAuth} from "../contexts/AuthContext";
import {makeStyles} from "@material-ui/core";
import Card from "@material-ui/core/Card";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import {instance} from "../api";
import * as constants from "../constants";
import Alert from "@material-ui/lab/Alert";
import CircularProgress from "@material-ui/core/CircularProgress";

const useStyles = makeStyles(theme => ({
    root: {
        display: "flex",
        marginTop: theme.spacing(4)
    },
    media: {
        width: "200px",
        height: "200px"
    },
    alert: {
        marginTop: theme.spacing(3)
    }
}))

const Profile = () => {
    const {isAuthenticated, dispatch} = useAuth()
    const [currentUser, setCurrentUser] = useState({})
    const [errors, setErrors] = useState({})
    const [loading, setLoading] = useState(true)
    const history = useHistory()
    const classes = useStyles()

    useEffect(() => {
        if (!isAuthenticated)
            history.push('/login?next=/profile')
    }, [isAuthenticated, history])

    // api.js文件中的请求拦截器自动携带access token
    async function fetchUser() {
        try {
            const response = await instance.get('/users/me/')
            const user = await response.data
            setCurrentUser(user)
            setLoading(false)
        } catch (e) {
            setLoading(false)
            setCurrentUser({})
            if (e.response && e.response.status === 401) {
                setErrors({detail: '登录会话已过期，请重新登录'})
                // token已经过期
                dispatch({type: constants.ACCESS_TOKEN_EXPIRED})
            }
        }
    }

    useEffect(() => {
        fetchUser()
    }, [])

    return (
        <>
            <Nav/>
            <Container>
                {loading && <CircularProgress/>}

                {errors.detail && (
                    <Alert severity="error" className={classes.alert}>{errors.detail}</Alert>
                )}

                {!!!errors.detail && (
                <Card className={classes.root}>
                    <CardMedia
                        className={classes.media}
                        image="/media/avatar.png"
                        title="avatar"
                    />
                    <CardContent>
                        <Typography gutterBottom variant="h5" component="h2">
                            {currentUser.username} / {currentUser.email}
                        </Typography>
                        <Typography variant="body2" color="textSecondary" component="p">
                            这里为个人简介信息
                        </Typography>
                    </CardContent>
                </Card>
                )}
            </Container>
        </>
    );
};

export default Profile;